﻿using DemoWebapi01.Entities;
using DemoWebapi01.Models;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace DemoWebapi01.MyServices
{
    public class AuthService : IAuthService
    {
        private readonly IConfiguration _config;
        private readonly JwtSettings _jwtSettings;

        public AuthService(IConfiguration config, IOptions<JwtSettings> jwtSettings)
        {
            _config = config;
            _jwtSettings = jwtSettings.Value;
        }
        public string GenerateJwtToken(User user, IList<string>? roles = null)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName?? string.Empty),
                new Claim(ClaimTypes.Email, user.Email ?? string.Empty)
            };

            // 添加角色声明
            if (user?.Roles?.Count > 0)
            {
                foreach (var role in user.Roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role.RoleName ?? ""));
                }
            }
            else if (roles != null && roles.Count > 0)
            {
                foreach (var role in roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddMinutes(_jwtSettings.ExpirationMinutes);

            var token = new JwtSecurityToken(
                issuer: _jwtSettings.Issuer,
                audience: _jwtSettings.Audience,
                claims: claims,
                expires: expires,
                signingCredentials: creds
            );

            var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

            return tokenString;
        }
    }
}
